import { IUploadFileRes } from '@/api/login.typings'
/**
 * 将图片URL转换为Base64编码
 * @param source - 可以是完整的上传响应对象或图片URL字符串
 * @param fallbackMimeType - 可选的后备MIME类型（当source是字符串时使用）
 * @returns Promise 解析后的base64字符串
 */
export const imageUrlToBase64 = async (
  source: IUploadFileRes | string,
  fallbackMimeType?: string,
): Promise<string> => {
  // 处理传入参数
  let url: string
  let mimeType: string

  if (typeof source === 'object') {
    url = source.url
    mimeType = source.mimeType || fallbackMimeType || 'image/jpeg'
  } else {
    url = source
    mimeType = fallbackMimeType || detectMimeTypeFromUrl(source) || 'image/jpeg'
  }

  return new Promise((resolve, reject) => {
    uni.downloadFile({
      url,
      success: (downloadRes) => {
        if (downloadRes.statusCode !== 200) {
          reject(new Error(`下载失败: HTTP ${downloadRes.statusCode}`))
          return
        }

        // 使用uni-app文件系统API读取文件内容
        uni.getFileSystemManager().readFile({
          filePath: downloadRes.tempFilePath,
          encoding: 'base64',
          success: (readRes) => {
            resolve(`data:${mimeType};base64,${readRes.data}`)
          },
          fail: (readErr) => {
            reject(new Error(`文件读取失败: ${readErr.errMsg}`))
          },
        })
      },
      fail: (downloadErr) => {
        reject(new Error(`下载失败: ${downloadErr.errMsg}`))
      },
    })
  })
}

/**
 * 根据URL后缀名推断MIME类型
 * @param url - 图片URL
 * @returns 推断的MIME类型或undefined
 */
const detectMimeTypeFromUrl = (url: string): string | undefined => {
  const ext = url.split('.').pop()?.toLowerCase()

  return ext
    ? {
        jpg: 'image/jpeg',
        jpeg: 'image/jpeg',
        png: 'image/png',
        gif: 'image/gif',
        bmp: 'image/bmp',
        webp: 'image/webp',
      }[ext]
    : undefined
}
